package org.ruoyi.common.chat.openai;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.ruoyi.common.chat.entity.chat.Message;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import java.util.*;

public class CcbAiClient {
    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * CCB大模型返回结构体
     */
    public static class CcbResult {
        private String content;
        private String reasoningContent;
        private String codeid;

        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
        public String getReasoningContent() { return reasoningContent; }
        public void setReasoningContent(String reasoningContent) { this.reasoningContent = reasoningContent; }
        public String getCodeid() { return codeid; }
        public void setCodeid(String codeid) { this.codeid = codeid; }
        @Override
        public String toString() {
            return "CcbResult{" +
                    "content='" + content + '\'' +
                    ", reasoningContent='" + reasoningContent + '\'' +
                    ", codeid='" + codeid + '\'' +
                    '}';
        }
    }

    /**
     * 调用CCB大模型接口，返回结构化结果
     */
    @SuppressWarnings("unchecked")
    public CcbResult chatCompletionCcb(String apiUrl, String apiKey, String modelId, List<Message> messages) {
        try {
            String traceId = "test-" + System.currentTimeMillis();
            // 1. 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("Tx-Code", "TA238FZ01");
            headers.set("Sec-Node-No", "400136");
            headers.set("Trace-Id", traceId);
            headers.set("Access_Key_Id", apiKey);
            headers.set("Host", "ai-scorpion.itech.ccb.com");
            headers.setContentType(MediaType.APPLICATION_JSON);
            // 2. 构建dataCntnt
            Map<String, Object> dataCntnt = new HashMap<>();
            dataCntnt.put("userId", "test");
            dataCntnt.put("sessionId", "123455");
            dataCntnt.put("messages", messages);
            dataCntnt.put("countTokens", true);
            dataCntnt.put("echo", true);
            dataCntnt.put("stream", false);
            Map<String, Object> modelConfig = new HashMap<>();
            modelConfig.put("model", modelId);
            modelConfig.put("temperature", 0.6);
            modelConfig.put("top_p", 0.9);
            modelConfig.put("top_k", 20);
            modelConfig.put("max_tokens", 40960000);
            dataCntnt.put("model_config", modelConfig);
            // 3. 构建requestBody
            Map<String, Object> requestBody = new HashMap<>();
            Map<String, Object> msgHead = new HashMap<>();
            msgHead.put("sys_evt_trace_id", traceId);
            requestBody.put("msgHead", msgHead);
            requestBody.put("Data_cntnt", objectMapper.writeValueAsString(dataCntnt));
            requestBody.put("Fst_Attr_Rmrk", apiKey);
            // 4. 发送POST请求
            HttpEntity<String> entity = new HttpEntity<>(objectMapper.writeValueAsString(requestBody), headers);
            ResponseEntity<Map> response = restTemplate.postForEntity(apiUrl, entity, Map.class);
            // 5. 解析返回体
            CcbResult result = new CcbResult();
            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                Map<String, Object> body = response.getBody();
                Object cResponseBody = body.get("C-Response-Body");
                if (cResponseBody instanceof Map) {
                    Object dataEnqrRslt = ((Map<?, ?>) cResponseBody).get("Data_Enqr_Rslt");
                    Object codeidObj = ((Map<?, ?>) cResponseBody).get("codeid");
                    if (codeidObj != null) {
                        result.setCodeid(codeidObj.toString());
                    }
                    if (dataEnqrRslt instanceof String) {
                        Map dataEnqrRsltMap = objectMapper.readValue((String) dataEnqrRslt, Map.class);
                        List choices = (List) dataEnqrRsltMap.get("choices");
                        if (choices != null && !choices.isEmpty()) {
                            Map choice = (Map) choices.get(0);
                            Map messagesMap = (Map) choice.get("messages");
                            if (messagesMap != null) {
                                Object contentObj = messagesMap.get("content");
                                if (contentObj != null) {
                                    result.setContent(contentObj.toString());
                                }
                                Object reasoningObj = messagesMap.get("reasoning_content");
                                if (reasoningObj != null) {
                                    result.setReasoningContent(reasoningObj.toString());
                                }
                            }
                        }
                    }
                }
            }
            return result;
        } catch (Exception e) {
            throw new RuntimeException("CCB大模型调用异常: " + e.getMessage(), e);
        }
    }
} 

